<template>
    <el-form-item :label="label" :prop="prop" :rules="rules">
        <el-select v-model="selectedCategoryId" :disabled="disabled" filterable remote clearable reserve-keyword
            :remote-method="remoteSearch" :loading="loading" :placeholder="placeholder" @change="handleChange">
            <el-option v-for="category in options" :key="category.id" :label="category.name" :value="category.id">
                <span style="float: left">{{ category.name }}</span>
            </el-option>
        </el-select>
    </el-form-item>
</template>

<script>
import { ElMessage } from 'element-plus'
import { DataPage } from '../../network/communicationConverter'
import { Definition } from '../../engine/common/definition'

export default {
    name: 'CategorySelect',
    props: {
        modelValue: {
            type: Object,
            default: null
        },
        label: {
            type: String,
            default: '商品分类'
        },
        prop: {
            type: String,
            default: 'category'
        },
        disabled: {
            type: Boolean,
            default: false
        },
        placeholder: {
            type: String,
            default: '请输入关键词搜索分类'
        },
        rules: {
            type: Array,
            default: () => []
        },
        basicUiAction: {
            type: Object,
            required: true
        }
    },
    emits: ['update:modelValue', 'change'],
    data() {
        return {
            selectedCategoryId: null, // 用整个对象
            options: [],  // 存储下拉选项
            loading: false,
            lastQuery: ''
        }
    },
    watch: {
        modelValue: {
            immediate: true,
            handler(val) {
                // 初始化时，将 modelValue 传入的对象赋值给 selectedCategory
                if (val) {
                    this.selectedCategoryId = val.id; // 更新 selectedUnitId 为 ID
                }
            }
        }
    },
    methods: {
        // 远程搜索分类
        async remoteSearch(query) {
            if (query === this.lastQuery) return;

            if (!this.basicUiAction) return;

            this.lastQuery = query;
            this.loading = true;

            try {
                const res = await this.basicUiAction.getCommodityCategory(
                    new DataPage(1, 0, Definition.gDefualPageSize),
                    { lke_categoryName: query }
                );

                if (res.data && res.data.dataList.length > 0) {
                    this.options = res.data.dataList;
                }
            } catch (error) {
                console.error('搜索分类失败:', error);
                ElMessage.error('搜索分类失败');
            } finally {
                this.loading = false;
            }
        },

        // 处理选项变化
        handleChange(val) {
            // 选项变化时，更新父组件的 modelValue 为选中的完整对象
            const selectedCategory = this.options.find(u => u.id === val)
            if (selectedCategory) {
                // 更新 `commodity.unit` 为完整对象
                this.$emit('update:modelValue', selectedCategory)
                this.$emit('change', selectedCategory)
            }
        },

        // 加载默认分类选项
        async loadDefaultOptions() {
            if (!this.basicUiAction) return;

            this.loading = true;
            try {
                const res = await this.basicUiAction.getCommodityCategory(
                    new DataPage(1, 0, Definition.gDefualPageSize)
                );

                if (res.data && res.data.dataList.length > 0) {
                    this.options = res.data.dataList;
                }
            } catch (error) {
                console.error('加载分类失败:', error);
            } finally {
                this.loading = false;
            }
        }
    },
    mounted() {
        // 初始化加载选项
        this.loadDefaultOptions();
    }
}
</script>
